package ntd.util.frame.action.ai;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.db.Db;
import cn.hutool.db.Entity;
import cn.hutool.db.Page;
import cn.hutool.db.sql.Direction;
import cn.hutool.db.sql.Order;
import cn.hutool.json.JSONUtil;
import cn.hutool.log.StaticLog;
import ntd.action.ActionAbs;
import ntd.action.bo.ActionInfo;
import ntd.action.bo.ActionOutBo;
import ntd.util.config.common.exception.ComException;
import ntd.util.frame.action.ActionPage;
import ntd.util.frame.data.factory.FactoryData;
import ntd.util.frame.javacv.tool.ToolAiUserSites;

import java.sql.SQLException;
import java.util.List;

public class ActionAiAlertInfo extends ActionAbs {

    @Override
    public ActionInfo info() {
        return new ActionInfo("AI告警信息", "ai-get-alert-info", new ActionAiAlertInfo());
    }

    @Override
    public ActionOutBo handle() {
        // 执行逻辑
        String mn = actionInBo.getParamStr("mn");
        String mns = actionInBo.getParamStr("mns");
        String startTime = actionInBo.getParamStr("startTime");
        String endTime = actionInBo.getParamStr("endTime");
        String model = actionInBo.getParamStr("model");

        //数据库
        Db use = Db.use(FactoryData.dataSource("272ab1b9c5cc4ea2b76302238247284c"));

        try {
            Page page = ActionPage.page(actionInBo, new Order("id", Direction.DESC));
            page.setPageNumber(page.getPageNumber() - 1);
            return new ActionOutBo(use.page(getWhereEntity(mn, mns, startTime, endTime,model), page));
        } catch (SQLException e) {
            StaticLog.error(e, "[AI][记录查询][{}]失败...", mn);
            throw new ComException("数据查询失败，请联系管理员或稍后重试...");
        }
    }

    private static Entity getWhereEntity(String mn, String mns, String startTime, String endTime,String model) {
        Entity whereEntity = Entity.create("airesult");
        whereEntity.set("isAlert", 1);
        // mns 封装
        List<String> currMns = ToolAiUserSites.getUserSiteMns(mn, mns);
        if (CollUtil.isNotEmpty(currMns)) {
            whereEntity.set("siteMn", currMns);
        }
        if (StrUtil.isAllNotBlank(startTime, endTime)) {
            whereEntity.set("create_time", StrUtil.format("between {} and {}", startTime, endTime));
        } else {
            if (StrUtil.isNotBlank(startTime)) {
                whereEntity.set("create_time", StrUtil.format("> {}", startTime));
            }
            if (StrUtil.isNotBlank(endTime)) {
                whereEntity.set("create_time", StrUtil.format("< {}", endTime));
            }
        }
        if (StrUtil.isNotBlank(model)){
            whereEntity.set("ai_mode_type", model);
        }
        return whereEntity;
    }


}
